package org.teamh.connection.json.handler;

import org.teamh.connection.json.event.JsonEventObject;
import org.teamh.game.Start;
import org.teamh.logic.datamodel.*;

public class UserHandler extends JsonMasterHandler {

	public UserHandler(Start start, DatamodelManager manager) {
		super(start, manager);
	}
	
	public boolean handleMsg(JsonEventObject json) {
		
		if (json.getSource().startsWith("User@")) {
			if (json.getProperty().equals("nickname")) {
				if (manager.getUser(json.getSource()) == null) {
					User user = new User(json.getSource());
					manager.addUser(user);
				}
				manager.getUser(json.getSource()).setNickname(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("team")) {
				User user = manager.getUser(json.getSource());
				if(user == null) {
					user = new User(json.getSource());
					manager.addUser(user);
				}
				
				if(json.getNewValue() != null) {
					Team team = manager.getTeam(json.getNewValue());
					if(team == null) {
						team = new Team(json.getNewValue());
						manager.addTeam(team);
					}
					
					user.setTeam(team);
				} else {
					user.setTeam(null);
				}
				return true;
			} else if (json.getProperty().equals("messages")) {
				//handle messages here
				//TODO
				return true;
			} else if (json.getProperty().equals("userAsset")) {
				User user = manager.getUser(json.getSource());
				if(user == null) {
					user = new User(json.getSource());
					manager.addUser(user);
				}
				
				if(json.getNewValue() != null) {
					UserAssets userAssets = manager.getUserAssets(json.getNewValue());
					if(userAssets == null) {
						userAssets = new UserAssets(json.getNewValue());
						manager.addUserAssets(userAssets);
					}
					
					user.setUserAssets(userAssets);
				} else {
					user.setUserAssets(null);
				}
				return true;
			}
			return false;
		} else {
			return false;
		}	
	}
}